package com.hongxun.modules.api.rest;

import com.alibaba.fastjson.JSON;
import com.hongxun.common.utils.R;
import com.hongxun.modules.api.annotation.AuthIgnore;
import com.hongxun.modules.bss.entity.DPictureEntity;
import com.hongxun.modules.bss.service.DPictureService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by admin on 2018/9/10.
 */
@RestController
@RequestMapping("/rest/photo")
public class PhotoController {

    @Autowired
    private ResourceLoader resourceLoader;

    @Value("${com.hongxun.IMAGEROTT}")
    private String ROOT;


    @Autowired
    DPictureService dPictureService;

//    /**
//     * 显示图片
//     *
//     * @param filename
//     * @return
//     */
//    @GetMapping("/{filename:.+}")
//    @AuthIgnore
//    public ResponseEntity<?> getFile(@PathVariable String filename) {
//        try {
//            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
//        } catch (Exception e) {
//            return ResponseEntity.notFound().build();
//        }
//    }

    /**
     * 显示图片
     *
     * @param address
     * @param response
     * @throws IOException
     */
    @AuthIgnore
    @GetMapping(value = "queryPic")
    public void queryPic(@RequestParam(required = false) String address, HttpServletResponse response) throws IOException {
        if (address != null) {
            response.setContentType("image/jpeg");
            File file=new File(ROOT +   address);
            if(file.exists()) {
                FileInputStream is = new FileInputStream(ROOT + address);
                if (is != null) {
                    int i = is.available(); // 得到文件大小
                    byte data[] = new byte[i];
                    is.read(data); // 读数据
                    is.close();
                    response.setContentType("image/jpeg");  // 设置返回的文件类型
                    OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
                    toClient.write(data); // 输出数据
                    toClient.close();
                }
            }
        }
    }

    /**
     * 上传图片信息
     *
     * @param file
     * @param params
     * @return
     */
    @RequestMapping("/photoUpLoad")
    public R fileUpLoad(@RequestParam("fileName") MultipartFile file, @RequestParam Map<String, Object> params) {
        File f = new File(ROOT);
        if (!f.exists()) f.mkdir();
        String sPhoto = params.get("photo").toString();
        List<DPictureEntity> pictureEntities = JSON.parseArray(sPhoto, DPictureEntity.class);
        try {
            setFile(pictureEntities, file);
            dPictureService.insertOrReplaceOrDelete(pictureEntities);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }


    private void setFile(List<DPictureEntity> bean, MultipartFile attachment)
            throws IOException {
        File zipFile = null;
        if (attachment != null && attachment.getSize() > 0) {
            InputStream inputStream = null;
            try {
                inputStream = attachment.getInputStream();
                File tempDir = new File(ROOT);
                String uuid = UUID.randomUUID().toString();
                zipFile = new File(tempDir, uuid + ".zip");
                FileUtils.copyInputStreamToFile(inputStream, zipFile);
                // 解压文件
                unzip(zipFile, tempDir, bean);
                //TODO 图片插入数据库
            } catch (IOException e) {
                if (zipFile != null) {
                    FileUtils.deleteQuietly(zipFile);
                }
                throw e;
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }

    boolean setBeanName(List<DPictureEntity> bean, String oldName, String newName) {
        for (DPictureEntity d : bean) {
            if (d.getPName().equals(oldName)) {//如果有，则先判断图片是否已经存在。
                if (!TextUtils.isEmpty(d.getPServeraddress()) && new File(ROOT + d.getPServeraddress()).exists()) {
                    return true;
                } else {
                    d.setPServeraddress(newName);
                }
            }
        }
        return false;
    }

    void unzip(File file, File dir, List<DPictureEntity> bean) throws IOException {
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(file, Charset.forName("UTF-8"));
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry zipEntry = entries.nextElement();
                long l = System.currentTimeMillis();
                String fileName = l + zipEntry.getName();
                if (!setBeanName(bean, zipEntry.getName(), fileName)) {
                    File targetFile = new File(dir, fileName);
                    if (!zipEntry.isDirectory()) {
                        InputStream input = zipFile.getInputStream(zipEntry);
                        FileUtils.copyInputStreamToFile(input, targetFile);
                    } else {
                        targetFile.mkdirs();
                    }
                }
            }
        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(zipFile);
        }
    }

}